package com.mt.skyhoist.ui.activity;
import static com.mt.skyhoist.ui.activity.ScanDeviceService.Refresh;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.mt.skyhoist.R;
import com.mt.skyhoist.util.GlobalVariable;
import com.mt.skyhoist.util.bean.DeviceModel;
import com.mt.skyhoist.util.user.DeviceModelSource;
import com.mt.skyhoist.util.view.ModifingNameDialog;
import com.mt.skyhoist.util.view.ModifyNameDialog;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.base.MTSeriaBase;
import com.mt.sdk.ble.model.BLEBaseAction;
import com.mt.sdk.ble.model.ErroCode;
import com.mt.sdk.ble.model.WriteCharactAction;
import com.mt.sdk.ble.model.WriteCharactWithAckAction;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import  com.mt.skyhoist.util.view.DeviceView;

import java.util.List;


//蓝牙处理类
public class ScanActivity extends Activity {
    public static String GROUNPINDEX = "GROUNPINDEX"; // 分组名字

    private GlobalVariable mGlobalVariable;
    private MTBLEManager manger;
    private MTSeriaBase ble;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        mGlobalVariable = GlobalVariable.getinstance();
        mGlobalVariable.getFreeDeviceList().clear();  // 清空上次存在的设备

        this.manger = MTBLEManager.getInstance(getApplicationContext());
        ble = new MTSeriaBase(getApplicationContext(), manger);

        initView();

        getIntentData();

        clearSelected();

//        setListViewHeight();
    }

    // 获取设备名称
    private int groupIndex = -1;

    private void getIntentData() {
        Intent intent = getIntent();

        groupIndex = intent.getIntExtra(GROUNPINDEX, 0);
        scanresult_txt.setText("Station" + (groupIndex + 1));

        freeListadapter.notifyDataSetInvalidated();

        refreshScanResult();
    }

    // 初始化控件
    private TextView scanresult_txt;
    private ListView free_device_listview;
    private String selectmac;
    private Button cancle_btn;
    private Button ok_btn;
    private ListView linked_listview;
    private TextView available_tv;

    private void initView() {
        cancle_btn = findViewById(R.id.cancle_btn);
        ok_btn = findViewById(R.id.ok_btn);
        scanresult_txt = findViewById(R.id.scanresult_txt);
        linked_listview = findViewById(R.id.linked_listview);
        free_device_listview = findViewById(R.id.device_listview);
        available_tv = findViewById(R.id.available_tv);
        free_device_listview.setAdapter(freeListadapter);
        linked_listview.setAdapter(linkedListadapter);

        free_device_listview.setOnItemLongClickListener(new OnItemLongClickListener() { // 长按，修改名字

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                System.out.println("position->" + position);

                final DeviceModel deviceModel = mGlobalVariable.getFreeDeviceList().get(position);

                ModifyNameDialog dialog = new ModifyNameDialog(ScanActivity.this);
                dialog.setMessage("New name(10 words Max)");
                dialog.setName(deviceModel.getName());
                dialog.setListener(new ModifyNameDialog.OnBtnClickListener() {
                    @Override
                    public void OnConfirm(String newName) {
                        if (deviceModel.getName().equals(newName)) { // 如果没有更改名称，则直接返回
                            return;
                        }

                        modifyName(deviceModel.getMac(), newName);
                    }

                    @Override
                    public void OnCancel() {

                    }
                });
                dialog.show();

                return true;
            }
        });

        linked_listview.setOnItemLongClickListener(new OnItemLongClickListener() { // 长按，修改名字

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final DeviceModel deviceModel = mGlobalVariable.getDeviceGroup().get(groupIndex).get(position);

                ModifyNameDialog dialog = new ModifyNameDialog(ScanActivity.this);
                dialog.setMessage("New name(10 words Max)");
                dialog.setName(deviceModel.getName());
                dialog.setListener(new ModifyNameDialog.OnBtnClickListener() {
                    @Override
                    public void OnConfirm(String newName) {
                        if (deviceModel.getName().equals(newName)) { // 如果没有更改名称，则直接返回
                            return;
                        }
                        deviceModel.setName(newName);

                        DeviceModelSource.getInstance().update(deviceModel);

                        modifyName(deviceModel.getMac(), newName);
                    }

                    @Override
                    public void OnCancel() {

                    }
                });
                dialog.show();

                return true;
            }
        });

        free_device_listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DeviceModel deviceModel = mGlobalVariable.getFreeDeviceList().get(position);
                if (deviceModel.isSelectAble()) {
                    deviceModel.setSelectAble(false);
                    freeListadapter.notifyDataSetInvalidated();
                    refreshScanResult();
                    return;
                }
                if(!canSelectFree) {
                    return;
                }

                deviceModel.setSelectAble(true);

                freeListadapter.notifyDataSetInvalidated();
                refreshScanResult();

                if (deviceModel.getRssi() == 0) {  // 没有搜索到，就没必要去闪灯
                    return;
                }

                selectmac = deviceModel.getMac();

                sendSingle();
            }
        });

        linked_listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DeviceModel deviceModel = mGlobalVariable.getDeviceGroup().get(groupIndex).get(position);
                if (deviceModel.isSelectAble()) {
                    deviceModel.setSelectAble(false);
                    linkedListadapter.notifyDataSetInvalidated();
                    return;
                }

                deviceModel.setSelectAble(true);

                linkedListadapter.notifyDataSetInvalidated();

                selectmac = deviceModel.getMac();

                if (deviceModel.getRssi() == 0) {  // 没有搜索到，就没必要去闪灯
                    return;
                }
                sendSingle();
            }
        });

        cancle_btn.setOnClickListener(myOnClickListener);
        ok_btn.setOnClickListener(myOnClickListener);
    }

    private boolean canSelectFree = true;
    private void refreshScanResult() {
        int linkedSize = mGlobalVariable.getDeviceGroup().get(groupIndex).size();
        int freeSelectSize = 0;

        for (DeviceModel device : mGlobalVariable.getFreeDeviceList()) {
            if(device.isSelectAble()){
                freeSelectSize ++;
            }
        }

        if(linkedSize + freeSelectSize >= 8) {
            canSelectFree = false;
            available_tv.setText("MAX LINKED TO STATION");
        } else {
            canSelectFree = true;
            available_tv.setText("Available to Link");
        }

    }

    private void setListViewHeight() {
        ListAdapter listAdapter = linked_listview.getAdapter(); //得到ListView 添加的适配器
        if ((listAdapter == null) || (listAdapter.getCount() == 0)) {
            return;
        }

        View itemView = listAdapter.getView(0, null, linked_listview); //获取其中的一项
        itemView.measure(0, 0);
        int itemHeight = itemView.getMeasuredHeight(); //一项的高度
        int itemCount = listAdapter.getCount();//得到总的项数
        LinearLayout.LayoutParams layoutParams = null; //进行布局参数的设置
        if (itemCount <= 4) {
            layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight * itemCount);
        } else {
            layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight * 4);
        }
        linked_listview.setLayoutParams(layoutParams);
    }

    private void clearSelected(){
        for (int i = 0; i < mGlobalVariable.getDeviceGroup().get(groupIndex).size(); i++) {
            mGlobalVariable.getDeviceGroup().get(groupIndex).get(i).setSelectAble(false);
        }
        for (int i = 0; i < mGlobalVariable.getFreeDeviceList().size(); i++) {
            mGlobalVariable.getFreeDeviceList().get(i).setSelectAble(false);
        }
    }
    // 修改设备名称
    private void modifyName(String mac, final String name) {
        System.out.println("修改名称->" + name);
        pd = new ModifingNameDialog(ScanActivity.this);
        pd.setMessage("Modify...");
        pd.show();
//        pd = ProgressDialog.show(ScanActivity2.this, "wait", "Modify...", true, true,
//                new DialogInterface.OnCancelListener() {
//
//                    @Override
//                    public void onCancel(DialogInterface dialog) {
//                        ble.disConnect();
//                    }
//                });
        ble.connect(mac, 2, false, new MTSeriaBase.CallBack() {

            @Override
            public void reTryConnect(int lasttimes) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onManualDisConnect(ErroCode errocode) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onDisConnect(ErroCode errocode) {
                if ((pd != null) && (pd.isShowing())) {
                    pd.dismiss();
                }
                Toast.makeText(getApplicationContext(), "Control fail", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onDatasRecive(BluetoothGattCharacteristic rxd_charact, byte[] datas) {

            }

            @Override
            public void onConnect(ErroCode errocode) {
                if (errocode.getCode() != 0) {
                    System.out.println("onConnect->fail");
                    if ((pd != null) && (pd.isShowing())) {
                        pd.dismiss();
                    }
                    return;
                }

                ble.addWriteCmdsAction(new WriteCharactWithAckAction(null, null, ("AT+NAME[" + name + "]").getBytes(),
                        new BLEBaseAction.Option(1000)) {

                    @Override
                    public void onReciveDatas(BluetoothGattCharacteristic characteristic, byte[] datas) {
                        super.onReciveDatas(characteristic, datas);
                        if ((pd != null) && (pd.isShowing())) {
                            pd.dismiss();
                        }
                        ble.disConnect();

                        System.out.println("ack->" + (new String(datas)));
                    }

                    @Override
                    public void onFail(ErroCode erro) {
                        super.onFail(erro);
                        if ((pd != null) && (pd.isShowing())) {
                            pd.dismiss();
                        }
                        ble.disConnect();
                        System.out.println("onFail->" + erro.getMsg());
                    }

                });
            }
        });
    }

    // 蓝牙发送一下闪光命令
//    private ProgressDialog pd;
    private ModifingNameDialog pd;
    private void sendSingle() {
//        pd = ProgressDialog.show(ScanActivity2.this, "wait", "Look at the light.", true, true,
//                new DialogInterface.OnCancelListener() {
//
//                    @Override
//                    public void onCancel(DialogInterface dialog) {
//                        ble.disConnect();
//                    }
//                });
        pd = new ModifingNameDialog(ScanActivity.this);
        pd.setMessage("Look at the light.");
        pd.show();
        ble.connect(selectmac, 2, false, new MTSeriaBase.CallBack() {

            @Override
            public void reTryConnect(int lasttimes) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onManualDisConnect(ErroCode errocode) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onDisConnect(ErroCode errocode) {
                if ((pd != null) && (pd.isShowing())) {
                    pd.dismiss();
                }
                Toast.makeText(getApplicationContext(), "Control fail", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onDatasRecive(BluetoothGattCharacteristic rxd_charact, byte[] datas) {

            }

            @Override
            public void onConnect(ErroCode errocode) {
                if (errocode.getCode() != 0) {
                    System.out.println("onConnect->fail");
                    if ((pd != null) && (pd.isShowing())) {
                        pd.dismiss();
                    }
                    return;
                }

                ble.addWriteDatasAction(new WriteCharactAction(null, new byte[]{0x0A}, new BLEBaseAction.Option(1000)) {

                    @Override
                    public void onSuccess() {
                        System.out.println("onSuccess");
                        super.onSuccess();
                        if ((pd != null) && (pd.isShowing())) {
                            pd.dismiss();
                        }
                        ble.disConnect();
                    }

                    @Override
                    public void onFail(ErroCode erro) {
                        System.out.println("onFail");
                        super.onFail(erro);
                        if ((pd != null) && (pd.isShowing())) {
                            pd.dismiss();
                        }
                        ble.disConnect();
                        Toast.makeText(getApplicationContext(), "Control fail", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

    // 按钮监听
    private OnClickListener myOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (v == cancle_btn) {
                setResult(RESULT_CANCELED);
                finish();
                return;
            }

            if (v == ok_btn) {
                // 删除选中的已经存储的设备
                List<DeviceModel> linkedDevices = mGlobalVariable.getDeviceGroup().get(groupIndex);
                for (int i = linkedDevices.size() - 1; i >= 0; i--) {
                    DeviceModel device = linkedDevices.get(i);
                    if (!device.isSelectAble()) {
                        continue;
                    }
                    System.out.println("Truth delete->" + device.getName());
                    DeviceModelSource.getInstance().delete(device);
                    linkedDevices.remove(device);
                    mGlobalVariable.getDeviceList().remove(device);
                }

                // 添加选中的设备
                List<DeviceModel> freeDevices = mGlobalVariable.getFreeDeviceList();
                for (int i = 0; i < freeDevices.size(); i++) {
                    DeviceModel device = freeDevices.get(i);
                    if (!device.isSelectAble()) {
                        continue;
                    }
                    System.out.println("Truth add->" + device.getName());
                    device.setSelectAble(false);
                    device.setGrounpId(groupIndex);

                    DeviceModelSource.getInstance().insert(device);
                    linkedDevices.add(device);
                    mGlobalVariable.getDeviceList().add(device);
                }
                setResult(RESULT_OK);
                finish();
            }

        }
    };

    // 列表适配器
    private BaseAdapter freeListadapter = new BaseAdapter() {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (null == convertView) {
                convertView = new DeviceView(getApplicationContext());
            }
            ((DeviceView) convertView).setStyle(false);
            ((DeviceView) convertView).setDatas(getItem(position));
            ((DeviceView) convertView).setStyle(false);

            return convertView;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public DeviceModel getItem(int position) {
            return mGlobalVariable.getFreeDeviceList().get(position);
        }

        @Override
        public int getCount() {
            return mGlobalVariable.getFreeDeviceList().size();
        }
    };

    // linked
    private BaseAdapter linkedListadapter = new BaseAdapter() {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (null == convertView) {
                convertView = new DeviceView(getApplicationContext());
            }

            ((DeviceView) convertView).setStyle(true);
            ((DeviceView) convertView).setDatas(getItem(position));
            ((DeviceView) convertView).setStyle(true);

            return convertView;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public DeviceModel getItem(int position) {
            return mGlobalVariable.getDeviceGroup().get(groupIndex).get(position);
        }

        @Override
        public int getCount() {
            if (groupIndex < 0) {
                return 0;
            }

            return mGlobalVariable.getDeviceGroup().get(groupIndex).size();
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);

        EventBus.getDefault().post(ScanDeviceService.StartScan);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);

        EventBus.getDefault().post(ScanDeviceService.StopScan);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Integer event) {
        switch (event) {
            case Refresh:
                freeListadapter.notifyDataSetInvalidated();
                break;
        }
    }


}